package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     * @return
     */
    @Override
    public Result listShopType() {
        // 从缓存中查询
        String key = "SHOP_TYPE";
        String shopType = stringRedisTemplate.opsForValue().get(key);

        // 缓存存在，直接返回
        if (StrUtil.isNotBlank(shopType)) {
            // 将Json字符串转为list
            List<ShopType> shopTypes = JSONUtil.toList(shopType, ShopType.class);
        }
        // 缓存不存在，查询数据库
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
        // 如果数据库中的数据不存在，抛异常
        if (shopTypeList.isEmpty()) {
            return Result.fail("店铺类型不存在");
        }
        // 将数据库查询到的数据转为Json字符串缓存到redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList));
        // 返回list集合
        return Result.ok(shopTypeList);
    }
}
